package com.yunxin.core.customer.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunxin.common.utils.OkHttpUtils;
import com.yunxin.core.admin.domain.AdminUser;
import com.yunxin.core.admin.service.AdminUserService;
import com.yunxin.core.customer.domain.CustomInfoAuthorizationLog;
import com.yunxin.core.customer.domain.CustomInfoRiskProbe;
import com.yunxin.core.customer.domain.CustomInfoRiskRadar;
import com.yunxin.core.customer.dto.RiskDTO;
import com.yunxin.core.customer.dto.RiskGetByUserDTO;
import com.yunxin.core.customer.dto.RiskGetByUserPageDTO;
import com.yunxin.core.customer.dto.RiskGetDTO;
import com.yunxin.core.customer.service.CustomInfoAuthorizationLogService;
import com.yunxin.core.customer.service.CustomInfoRiskProbeService;
import com.yunxin.core.customer.service.CustomInfoRiskRadarService;
import com.yunxin.core.customer.service.RiskManagementService;
import com.yunxin.core.customer.service.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RiskManagementServiceImpl implements RiskManagementService {

    @Value("${riskmanagement.url}")
    private String url;

    @Value("${riskmanagement.productCodeTZ}")
    private String productCodeTZ;

    @Value("${riskmanagement.productCodeLD}")
    private String productCodeLD;

    @Value("${riskmanagement.shopID}")
    private String shopID;

    @Value("${riskmanagement.accessKeySecret}")
    private String accessKeySecret;

    @Value("${riskmanagement.accessoryUrl}")
    private String accessoryUrl;

    @Value("${riskmanagement.riskswitch}")
    private boolean riskswitch;

    @Autowired
    private CustomInfoRiskProbeService customInfoRiskProbeService;
    @Autowired
    private CustomInfoRiskRadarService customInfoRiskRadarService;
    @Autowired
    private CustomInfoAuthorizationLogService customInfoAuthorizationLogService;
    @Autowired
    private AdminUserService adminUserService;

    //探针
    @Override
    public String getProbe(RiskDTO riskDTO, CustomInfoAuthorizationLog customInfoAuthorizationLog) {
        if (riskswitch){
            LambdaQueryWrapper<CustomInfoRiskProbe> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(CustomInfoRiskProbe::getAuthorizationLogId,customInfoAuthorizationLog.getId());
            long count = customInfoRiskProbeService.count(queryWrapper);
            if (count<1){
                Map<String, Object> map = new HashMap<>();
                map.put("shopId",shopID);
                map.put("productCode",productCodeTZ);
                map.put("name",riskDTO.getUserName());
                map.put("idNo",riskDTO.getIdNumber());
                map.put("mobile",riskDTO.getPhoneNumber());
                map.put("timestamp",String.valueOf(new Date().getTime()));
                try {
                    String sign = SignUtil.getSign(accessKeySecret, SignUtil.getParamsStr(map), "UTF-8");
                    map.put("sign",sign);
                    String post = OkHttpUtils.X.post(url, JSON.toJSONString(map));
                    if (StringUtils.isNotBlank(post)){
                        JSONObject jsonObject = JSON.parseObject(post);
                        CustomInfoRiskProbe customInfoRiskProbe=new CustomInfoRiskProbe();
                        customInfoRiskProbe.setCode(jsonObject.getString("returnCode"));
                        customInfoRiskProbe.setAuthorizationLogId(customInfoAuthorizationLog.getId());
                        customInfoRiskProbe.setMessage(jsonObject.getString("returnMsg"));
                        customInfoRiskProbe.setData(jsonObject.getString("data"));
                        customInfoRiskProbeService.save(customInfoRiskProbe);
                    }
                } catch (Exception e) {
                    log.error("请求探针接口发送异常 日志id："+customInfoAuthorizationLog.getId(),e);
                    CustomInfoRiskProbe customInfoRiskProbe=new CustomInfoRiskProbe();
                    customInfoRiskProbe.setAuthorizationLogId(customInfoAuthorizationLog.getId());
                    customInfoRiskProbe.setMessage("请求探针接口发送异常");
                    customInfoRiskProbe.setIsDel(1);
                    customInfoRiskProbeService.save(customInfoRiskProbe);
                }
            }
        }
        return "";
    }
    //全景雷达
    @Override
    public String getradar(RiskDTO riskDTO,CustomInfoAuthorizationLog customInfoAuthorizationLog) {
        if (riskswitch) {
            LambdaQueryWrapper<CustomInfoRiskRadar> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(CustomInfoRiskRadar::getAuthorizationLogId,customInfoAuthorizationLog.getId());
            long count = customInfoRiskRadarService.count(queryWrapper);
            if (count<1){
                Map<String, Object> map = new HashMap<>();
                map.put("shopId",shopID);
                map.put("productCode",productCodeLD);
                map.put("name",riskDTO.getUserName());
                map.put("idNo",riskDTO.getIdNumber());
                map.put("mobile",riskDTO.getPhoneNumber());
                map.put("timestamp",String.valueOf(new Date().getTime()));
                try {
                    String sign = SignUtil.getSign(accessKeySecret, SignUtil.getParamsStr(map), "UTF-8");
                    map.put("sign",sign);
                    String post = OkHttpUtils.X.post(url, JSON.toJSONString(map));
                    if (StringUtils.isNotBlank(post)){
                        JSONObject jsonObject = JSON.parseObject(post);
                        CustomInfoRiskRadar customInfoRiskRadar=new CustomInfoRiskRadar();
                        customInfoRiskRadar.setCode(jsonObject.getString("returnCode"));
                        customInfoRiskRadar.setAuthorizationLogId(customInfoAuthorizationLog.getId());
                        customInfoRiskRadar.setMessage(jsonObject.getString("returnMsg"));
                        customInfoRiskRadar.setData(jsonObject.getString("data"));
                        customInfoRiskRadarService.save(customInfoRiskRadar);
                    }
                } catch (Exception e) {
                    log.error("请求雷达接口发送异常 日志id："+customInfoAuthorizationLog.getId(),e);
                    CustomInfoRiskRadar customInfoRiskRadar=new CustomInfoRiskRadar();
                    customInfoRiskRadar.setAuthorizationLogId(customInfoAuthorizationLog.getId());
                    customInfoRiskRadar.setMessage("请求雷达接口发送异常");
                    customInfoRiskRadar.setIsDel(1);
                    customInfoRiskRadarService.save(customInfoRiskRadar);
                }
            }
        }
        return "";
    }

    @Override
    public String getAll(RiskDTO riskDTO, CustomInfoAuthorizationLog customInfoAuthorizationLog) {
        if (riskswitch) {
            String probe = this.getProbe(riskDTO, customInfoAuthorizationLog);
            String getradar = this.getradar(riskDTO, customInfoAuthorizationLog);
        }
        return "";
    }

    @Override
    public Long examineRiskManagement(RiskGetDTO riskGetDTO) {
        LambdaQueryWrapper<CustomInfoAuthorizationLog> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CustomInfoAuthorizationLog::getWechatCustomerId,riskGetDTO.getWechatCustomerId())
                .eq(CustomInfoAuthorizationLog::getIdNumber,riskGetDTO.getIdNumber())
                .eq(CustomInfoAuthorizationLog::getUserName,riskGetDTO.getUserName())
                .eq(CustomInfoAuthorizationLog::getPhoneNumber,riskGetDTO.getPhoneNumber())
                .orderByDesc(CustomInfoAuthorizationLog::getId)
                .last("limit 1");;
        CustomInfoAuthorizationLog customInfoAuthorizationLog = customInfoAuthorizationLogService.getOne(lambdaQueryWrapper);
        if (ObjectUtils.isEmpty(customInfoAuthorizationLog)||(new Date().getTime()) - customInfoAuthorizationLog.getCreateTime().getTime() > 2592000000L){
            customInfoAuthorizationLog=new CustomInfoAuthorizationLog();
            BeanUtils.copyProperties(riskGetDTO,customInfoAuthorizationLog);
            customInfoAuthorizationLogService.save(customInfoAuthorizationLog);
        }
        RiskDTO riskDTO=new RiskDTO();
        BeanUtils.copyProperties(riskGetDTO,riskDTO);
        this.getAll(riskDTO,customInfoAuthorizationLog);
        return customInfoAuthorizationLog.getId();
    }

    @Override
    public Long examineRiskManagement(RiskGetByUserDTO riskGetByUserDTO) {
        LambdaQueryWrapper<CustomInfoAuthorizationLog> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CustomInfoAuthorizationLog::getCreateUserId,riskGetByUserDTO.getCreateUserId())
                .eq(CustomInfoAuthorizationLog::getIdNumber,riskGetByUserDTO.getIdNumber())
                .eq(CustomInfoAuthorizationLog::getUserName,riskGetByUserDTO.getUserName())
                .eq(CustomInfoAuthorizationLog::getPhoneNumber,riskGetByUserDTO.getPhoneNumber())
                .orderByDesc(CustomInfoAuthorizationLog::getId)
                .last("limit 1");
        CustomInfoAuthorizationLog customInfoAuthorizationLog = customInfoAuthorizationLogService.getOne(lambdaQueryWrapper);
        if (ObjectUtils.isEmpty(customInfoAuthorizationLog)||(new Date().getTime()) - customInfoAuthorizationLog.getCreateTime().getTime() > 2592000000L){
            customInfoAuthorizationLog=new CustomInfoAuthorizationLog();
            BeanUtils.copyProperties(riskGetByUserDTO,customInfoAuthorizationLog);
            customInfoAuthorizationLogService.save(customInfoAuthorizationLog);
            RiskDTO riskDTO=new RiskDTO();
            BeanUtils.copyProperties(riskGetByUserDTO,riskDTO);
            this.getAll(riskDTO,customInfoAuthorizationLog);
        }
        return customInfoAuthorizationLog.getId();
    }

    @Override
    public CustomInfoAuthorizationLog getLogByid(Long logId) {
        return customInfoAuthorizationLogService.getById(logId);
    }

    @Override
    public List<CustomInfoAuthorizationLog> getRiskManagement(Long wechatCustomerId) {
        LambdaQueryWrapper<CustomInfoAuthorizationLog> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CustomInfoAuthorizationLog::getWechatCustomerId,wechatCustomerId).orderByDesc(CustomInfoAuthorizationLog::getId);
        List<CustomInfoAuthorizationLog> logs = customInfoAuthorizationLogService.list(lambdaQueryWrapper);
        if (ObjectUtils.isEmpty(logs)){
            return null;
        }
        Set<Long> logIds = logs.stream().map(i -> i.getId()).collect(Collectors.toSet());
        //客户风控探针C表
        LambdaQueryWrapper<CustomInfoRiskProbe> probeLambdaQueryWrapper=new LambdaQueryWrapper<>();
        probeLambdaQueryWrapper.in(CustomInfoRiskProbe::getAuthorizationLogId,logIds);
        List<CustomInfoRiskProbe> probeList = customInfoRiskProbeService.list(probeLambdaQueryWrapper);
        Map<Long, CustomInfoRiskProbe> probeMap = probeList.stream().collect(Collectors.toMap(CustomInfoRiskProbe::getAuthorizationLogId, obj -> obj));
        //全景雷达
        LambdaQueryWrapper<CustomInfoRiskRadar> radarLambdaQueryWrapper=new LambdaQueryWrapper<>();
        radarLambdaQueryWrapper.in(CustomInfoRiskRadar::getAuthorizationLogId,logIds);
        List<CustomInfoRiskRadar> radarList = customInfoRiskRadarService.list(radarLambdaQueryWrapper);
        Map<Long, CustomInfoRiskRadar> radarMap = radarList.stream().collect(Collectors.toMap(CustomInfoRiskRadar::getAuthorizationLogId, obj -> obj));
        for (CustomInfoAuthorizationLog customInfoAuthorizationLog : logs) {
            customInfoAuthorizationLog.setCustomInfoRiskProbe(probeMap.get(customInfoAuthorizationLog.getId()));
            customInfoAuthorizationLog.setCustomInfoRiskRadar(radarMap.get(customInfoAuthorizationLog.getId()));
        }
        return logs;
    }

    @Override
    public Page<CustomInfoAuthorizationLog> getRiskManagementPage(RiskGetByUserPageDTO riskGetByUserPageDTO) {
        LambdaQueryWrapper<CustomInfoAuthorizationLog> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(CustomInfoAuthorizationLog::getCreateUserId,riskGetByUserPageDTO.getCreateUserIdList())
                .like(!ObjectUtils.isEmpty(riskGetByUserPageDTO.getUserName()),CustomInfoAuthorizationLog::getUserName,riskGetByUserPageDTO.getUserName())
                .like(!ObjectUtils.isEmpty(riskGetByUserPageDTO.getPhoneNumber()),CustomInfoAuthorizationLog::getPhoneNumber,riskGetByUserPageDTO.getPhoneNumber())
                .like(!ObjectUtils.isEmpty(riskGetByUserPageDTO.getIdNumber()),CustomInfoAuthorizationLog::getIdNumber,riskGetByUserPageDTO.getIdNumber())
                .ge(!ObjectUtils.isEmpty(riskGetByUserPageDTO.getStartCreateTime()),CustomInfoAuthorizationLog::getCreateTime,riskGetByUserPageDTO.getStartCreateTime())
                .le(!ObjectUtils.isEmpty(riskGetByUserPageDTO.getEndCreateTime()),CustomInfoAuthorizationLog::getCreateTime,riskGetByUserPageDTO.getEndCreateTime())
                .orderByDesc(CustomInfoAuthorizationLog::getId);
        Page<CustomInfoAuthorizationLog> page=new Page<>(riskGetByUserPageDTO.getPageNum(),riskGetByUserPageDTO.getPageSize());
        customInfoAuthorizationLogService.page(page,lambdaQueryWrapper);
        List<CustomInfoAuthorizationLog> records = page.getRecords();
        Set<Long> userIds = records.stream().map(i -> i.getCreateUserId()).collect(Collectors.toSet());
        if (!userIds.isEmpty()){
            List<AdminUser> adminUserList = adminUserService.getAdminUserListByIds(userIds);
            Map<Integer, String> userMap = adminUserList.stream().collect(Collectors.toMap(obj -> obj.getId(), obj -> obj.getUsername()));
            for (CustomInfoAuthorizationLog record : records) {
                record.setCreateUserName(userMap.get(record.getCreateUserId().intValue()));
            }
        }

        return page;
    }

    @Override
    public CustomInfoAuthorizationLog getRiskManagementById(Long id) {
        CustomInfoAuthorizationLog customInfoAuthorizationLog = customInfoAuthorizationLogService.getById(id);
        if (ObjectUtils.isEmpty(customInfoAuthorizationLog)){
            return null;
        }
        //客户风控探针C表
        LambdaQueryWrapper<CustomInfoRiskProbe> probeLambdaQueryWrapper=new LambdaQueryWrapper<>();
        probeLambdaQueryWrapper.eq(CustomInfoRiskProbe::getAuthorizationLogId,id);
        CustomInfoRiskProbe probe = customInfoRiskProbeService.getOne(probeLambdaQueryWrapper);
        customInfoAuthorizationLog.setCustomInfoRiskProbe(probe);
        //全景雷达
        LambdaQueryWrapper<CustomInfoRiskRadar> radarLambdaQueryWrapper=new LambdaQueryWrapper<>();
        radarLambdaQueryWrapper.eq(CustomInfoRiskRadar::getAuthorizationLogId,id);
        CustomInfoRiskRadar riskRadar = customInfoRiskRadarService.getOne(radarLambdaQueryWrapper);
        customInfoAuthorizationLog.setCustomInfoRiskRadar(riskRadar);
        return customInfoAuthorizationLog;
    }
}
